package main

import (
	"fmt"
	"sync"
)

func main() {
	c1, c2 := make(chan bool), make(chan string)
	c3 := make(chan bool)

	go func() {
		for flag1, flag2 := false, false; !flag1 || !flag2; {
			select {
			case v, ok := <-c1:
				if !ok {
					if !flag1 {
						flag1 = true
						c3 <- true
					}
					break
				}
				fmt.Println("c1", v)
			case v, ok := <-c2:
				if !ok {
					if !flag2 {
						flag2 = true
						c3 <- true
					}
					break
				}
				fmt.Println("c2", v)
			}
		}
	}()

	c1 <- false
	c2 <- "hello"
	c1 <- true
	c2 <- "world"
	close(c1)
	close(c2)

	for i := 0; i < 2; i++ {
		<-c3
	}
	fmt.Println("done")

	//随机打印0和1
	c := make(chan int)
	go func() {
		for {
			s, _ := <-c
			fmt.Println(s)
		}
	}()
	for i := 0; i < 10; i++ {
		select {
		case c <- 0:
		case c <- 1:
		}
	}

	//相互发送消息
	c4, c5 := make(chan string), make(chan string)
	wg := &sync.WaitGroup{}
	wg.Add(2)
	go func() {
		for {
			a := <-c4
			fmt.Println(a)
			c5 <- "world"
		}
	}()
	go func() {
		for {
			c4 <- "hello"
			a := <-c5
			fmt.Println(a)
			wg.Done()
		}
	}()
	wg.Wait()
}
